# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSMaintenanceDoc(Document):
	def before_insert(self):
		add_days = 0
		# frappe.utils.getdate()获取的是datetime对象, frappe.utils.today()获取得出字符串
		today = frappe.utils.getdate()
		if self.periodicity == 'Daily': add_days = 1
		if self.periodicity == 'Weekly': add_days = 7
		if self.periodicity == 'Monthly': add_days = 30
		if self.periodicity == 'Quarterly': add_days = 90
		if self.periodicity == 'Half-yearly': add_days = 180
		if self.periodicity == 'Yearly': add_days = 360
		if self.periodicity == '2 Yearly': add_days = 720
		if self.periodicity == '3 Yearly': add_days = 1080

		if not frappe.db.exists({"doctype": self.doctype, "equipment_card": self.equipment_card, "maintenance_plan": self.maintenance_plan}):
			self.maintenance_next_date = frappe.utils.add_to_date(self.expected_maintenance_date, days=add_days)
			
		else:
			# 根据当前equipment_card和maintenance_stoped并且maintenance_plan相同查找expected_maintenance_date最新的保养单, 获取expected_maintenance_date和maintenance_date
			date_dict = frappe.get_all(	self.doctype, filters={"equipment_card": self.equipment_card, "maintenance_plan": self.maintenance_plan,"maintenance_stoped": 0}, fields=["maintenance_date", "expected_maintenance_date", "name"], order_by="expected_maintenance_date desc", page_length=1, as_list=True)[0]
			if date_dict[0]:
				# 给expected_maintenance_date赋值: 此赋值不能小于today(), 否则就是joke
				if frappe.utils.add_to_date(date_dict[0], days=add_days) >= today:
					self.expected_maintenance_date = frappe.utils.add_to_date(date_dict[0], days=add_days)
					self.maintenance_next_date = frappe.utils.add_to_date(self.expected_maintenance_date, days=add_days)
				else:
					self.expected_maintenance_date = today
					self.maintenance_next_date = frappe.utils.add_to_date(self.expected_maintenance_date, days=add_days)
			else:
				if frappe.utils.add_to_date(date_dict[1], days=add_days) >= today:
					self.expected_maintenance_date = frappe.utils.add_to_date(date_dict[1], days=add_days)
					self.maintenance_next_date = frappe.utils.add_to_date(self.expected_maintenance_date, days=add_days)
				else:
					self.expected_maintenance_date = today
					self.maintenance_next_date = frappe.utils.add_to_date(self.expected_maintenance_date, days=add_days)

	def before_save(self):
		if self.maintenance_date:
			if self.maintenance_date > frappe.utils.today():
				frappe.throw("实际保养日期不允许大于今天日期!")

	def before_submit(self):
		if not self.maintenance_man or not self.maintenance_date:
			frappe.throw("实际保养日期或实际保养人不允许为空!")
		if not self.items:
			frappe.throw("保养表不允许为空!")
		if self.items:
			for item in self.items:
				if not item.maintenance_result:
					frappe.throw(f"保养表第{item.idx} 行保养结果为空!")